<template>
  <div class="form_dialog">
    <!-- 编辑组织人员弹框 -->
    <el-dialog
      v-model="visible"
      :title="`${form.groupName}成员`"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="20vh"
      center
      width="400px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="select_header">
          <el-select
            v-model="selectedUserId"
            value-key="id"
            filterable
            placeholder="请选择"
            size="small"
          >
            <el-option
              v-for="item in userSelectList"
              :key="item.id"
              :label="item.truename || item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="createMember">
            添加
          </el-button>
        </div>
        <div class="user_list">
          <div v-if="groupMemberList.length" class="user_list_content">
            <div
              v-for="(item, i) in groupMemberList"
              :key="i"
              class="user_list_item"
            >
              <UserAvatar
                :src="item.avatar"
                :showHuangguan="item.isLeader"
                :size="30"
              />
              <div class="name_box">{{ item.truename || item.nickname }}</div>
              <el-button
                v-if="!item.isLeader"
                type="warning"
                size="mini"
                @click="setLeader(item, i)"
                plain
              >
                设为组长
              </el-button>
              <el-button
                type="danger"
                size="mini"
                @click="deleteMember(item, i)"
                plain
              >
                删除
              </el-button>
            </div>
          </div>
          <el-empty v-else description="暂无数据"></el-empty>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance, computed } from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import UserAvatar from "../../../components/UserAvatar.vue";
import { cloneDeep } from "lodash";

const initFormData = () => {
  return {
    groupId: null,
    groupName: null,
    userIds: [],
    leaderId: null,
    orgId: null,
  };
};

export default {
  name: "GroupUserFormDialog",
  components: { UserAvatar },
  props: {
    orgId: Number,
  },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单数据
    const form = reactive(initFormData());
    // 编辑还是新增
    const isEdit = ref(false);
    // 用户下拉列表数据
    const userSelectList = ref([]);
    // 选择的用户 id 集合
    const selectedUserIds = ref([]);
    const selectedUserId = ref(null);
    // 组织的成员列表
    const groupMemberList = ref([]);

    // 打开弹框
    const open = (row) => {
      if (row) {
        form.groupName = row.groupName;
        form.groupId = row.id;
        isEdit.value = true;
        listUserByGroupId();
      } else {
        // 新增
        isEdit.value = false;
      }
      form.orgId = props.orgId;
      visible.value = true;
      getUserSelectList();
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
      context.emit("refresh");
    };

    // 重置数据
    const resetData = () => {
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
      groupMemberList.value = [];
      userSelectList.value = [];
      selectedUserIds.value = [];
      selectedUserId.value = null;
    };

    // 获取没有组织的人员数据
    const getUserSelectList = () => {
      $api.users
        .listHasNotGroupUser({
          orgId: props.orgId,
        })
        .then((res) => {
          userSelectList.value = res.data;
        })
        .catch((err) => {
          console.error("getUserSelectList error: ", err);
        });
    };

    // 查询组织成员
    const listUserByGroupId = () => {
      dialogLoading.value = true;
      $api.users
        .listUserByGroupId({
          groupId: form.groupId,
        })
        .then((res) => {
          groupMemberList.value = res.data;
        })
        .catch((err) => {
          console.error("listUserByGroupId error: ", err);
        })
        .finally(() => {
          dialogLoading.value = false;
        });
    };

    // 添加成员
    const createMember = () => {
      if (!selectedUserId.value) {
        ElMessage.warning("请先选择用户");
      }
      dialogLoading.value = true;
      $api.users
        .userBindGroup({
          userId: selectedUserId.value,
          groupId: form.groupId,
        })
        .then((res) => {
          listUserByGroupId();
          getUserSelectList();
        })
        .catch((err) => {
          dialogLoading.value = false;
          console.error("userBindGroup error: ", err);
        });
    };

    // 设为组长
    const setLeader = (item, index) => {
      dialogLoading.value = true;
      $api.users
        .setGroupManager({
          userId: item.id,
        })
        .then((res) => {
          listUserByGroupId();
          getUserSelectList();
        })
        .catch((err) => {
          dialogLoading.value = false;
          console.error("setGroupManager error: ", err);
        });
    };

    // 删除成员
    const deleteMember = (item, index) => {
      dialogLoading.value = true;
      $api.users
        .userUnboundGroup({
          userId: item.id,
        })
        .then((res) => {
          listUserByGroupId();
          getUserSelectList();
        })
        .catch((err) => {
          dialogLoading.value = false;
          console.error("userUnboundGroup error: ", err);
        });
    };

    // 计算属性
    const userInfo = computed(() => store.state.user.userInfo);

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      form,
      open,
      close,
      isEdit,
      userSelectList,
      userInfo,
      selectedUserIds,
      selectedUserId,
      groupMemberList,
      createMember,
      deleteMember,
      setLeader,
    };
  },
};
</script>

<style lang="less" scoped>
.dialog_container {
  height: 350px;
  display: flex;
  flex-direction: column;
  .select_header {
    width: 100%;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  .user_list {
    flex: 1;
    overflow: hidden auto;
    .user_list_item {
      display: flex;
      align-items: center;
      padding: 10px 20px;
    }
    .name_box {
      flex: 1;
      overflow: hidden;
      margin: 0 20px;
    }
  }
}
.dialog_footer {
}
</style>
